<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://localhost:5050/socket.io/socket.io.js"></script>
    <style>
        *{margin: 0;
        padding: 0;}
        .chatpage{
            padding: 80px;
            height: 80vh;
            display: flex;
            flex-direction: column;
        }
        .chatbox{
          flex:1;
          background-color: #f0f0f0;
          padding: 15px;
        }
        .msgbox{
            height: 100px;
            display: flex;
        }
        .msgbox textarea{flex:1;}
        .msgbox button{ width: 100px;}
        .user{text-align: right; color:dodgerblue;}
    </style>
</head>
<body>
    <div class="chatpage">
        <div class="chatbox" id="chatbox">

        </div>
        <div class="msgbox">
            <textarea name="" id="msgbox" width="100%" cols="30" rows="10"></textarea>
            <button onclick="sendMsg()">发送</button>
        </div>
        </div>
    <script>
        this.userid = new Date().getTime();
        this.username = new Date().getTime()+"匿名";
        this.socket = io.connect("ws://localhost:5050");
        this.socket.on("message",(obj)=>{
            console.log(obj);
            let div = document.createElement("div");
            if(obj.userid==this.userid){
                div.className = "user"
            }
            div.innerHTML = obj.msg;
            chatbox.append(div);
        })
        function sendMsg(){
            let msg = msgbox.value;
            let obj = {msg,userid:this.userid,username:this.username};
            this.socket.emit("message",obj);
            msgbox.value="";
        }

    </script>
    
</body>
</html>